# 构建阶段
FROM swr.cn-north-4.myhuaweicloud.com/ddn-k8s/docker.io/node:18-alpine AS builder


# 设置工作目录
WORKDIR /app

# 临时变量 tmpFile 赋值 /tmp/repo
ARG tmpFile=/tmp/repo

# 配置华为云Alpine镜像源
RUN sed -i 's@https://dl-cdn.alpinelinux.org@https://mirrors.huaweicloud.com@g' /etc/apk/repositories
# 安装必要的依赖
RUN apk add --no-cache \
    git \
    && rm -rf /var/cache/apk/*

# 从 Git 仓库克隆源码到临时目录
ARG CACHE_DATE=not_latest
RUN git clone https://gitee.com/JIULANG9/class-schedule.git $tmpFile; 

# 复制根目录的内容到当前工作目录
RUN cp -r $tmpFile/* . && \
    cp -r $tmpFile/.* . 2>/dev/null || true

# 清理临时文件
RUN rm -rf $tmpFile

# 添加构建参数，以便在构建时注入
ARG NEXT_PUBLIC_API_BASE_URL
ENV NEXT_PUBLIC_API_BASE_URL=$NEXT_PUBLIC_API_BASE_URL

# 安装依赖
RUN npm ci

# 构建应用
RUN npm run build

# 生产阶段
FROM swr.cn-north-4.myhuaweicloud.com/ddn-k8s/docker.io/node:18-alpine AS runner
WORKDIR /app

ENV NODE_ENV production
# 添加构建参数
ARG NEXT_PUBLIC_API_BASE_URL
ENV NEXT_PUBLIC_API_BASE_URL=$NEXT_PUBLIC_API_BASE_URL

# 创建非root用户
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

# 复制standalone输出目录
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/public ./public

# 设置正确的权限
RUN chown -R nextjs:nodejs /app
USER nextjs

# 暴露端口
EXPOSE 3000

ENV PORT 3000
ENV HOSTNAME "0.0.0.0"

# 启动Next.js
CMD ["node", "server.js"]